# !/bin/sh -
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: download.sh
# author: david921518@qq.com

. /usr/lib/kpc/posix-arrays.sh

################
# global vars
GLB_WORK_DIR=
GLB_PREINSTALL_ROOT=
GLB_PREINSTALL_LIST=
################

whoami=$(which whoami)
if [ x"$whoami" == x ]; then
  user="$USER"
else
  user=$(whoami)
fi

# 定义日志格式-前缀
log_prefix="[download]"
# 定义日志目录和文件名
log_file_dir="/var/log/kpc/huangdi"
log_file_path="$log_file_dir/bootstrap.log"

log_kmsg_path="/dev/kmsg"
log_con_path="/dev/tty1"

function log_init()
{
  # 文件不存在则创建
  if [ ! -d "$log_file_dir" ]; then
    mkdir -p $log_file_dir
    chmod -R 755 $log_file_dir
  fi
  if [ ! -f "$log_file_path" ]; then
    touch $log_file_path
  fi
}

# 定义日志打印格式
function log()
{
  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")
  echo "$curtime $log_prefix $@"
  if [ "$user" == "root" ]; then
    echo "$curtime $log_prefix $@" >>$log_file_path
    #sleep 1
    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    #sleep 1
    #echo "$curtime $log_prefix [con] $@" >$log_con_path
    #sleep 1
  fi
}

function log_from_file()
{
  tmpfile=$@
  if [ ! -f "$tmpfile" ]; then
    log "no file [$tmpfile] to log"
    return 1
  fi

  declare_i_arr lists
  while IFS= read -r line;
  do
    add_i_arr_el lists "$line"
  done <$tmpfile

  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")

  #echo "$curtime $log_prefix $@"
  local i=0
  get_i_arr_indices lists indices
  for i in $indices
  do
    #log "lists[$i]=[${lists[i]}]"
    get_i_arr_val lists $i line
    #log "line=[$line]"
    echo "$curtime $log_prefix ${line}"
  done

  if [ "$user" == "root" ]; then
    #echo "$curtime $log_prefix $@" >>$log_file_path
    i=0
    get_i_arr_indices lists indices
    for i in $indices
    do
      get_i_arr_val lists $i line
      echo "$curtime $log_prefix ${line}" >>$log_file_path
    done

    #sleep 1

    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    #i=0
    #get_i_arr_indices lists indices
    #for i in $indices
    #do
    #  get_i_arr_val lists $i line
    #  echo "$curtime $log_prefix ${line}" >$log_kmsg_path
    #  [ $((i%10)) -ne 9 ] || sleep 1
    #done

    #sleep 1

    #echo "$curtime $log_prefix [con] $@" >$log_con_path
    #i=0
    #get_i_arr_indices lists indices
    #for i in $indices
    #do
    #  get_i_arr_val lists $i line
    #  echo "$curtime $log_prefix ${line}" >$log_con_path
    #done

    #sleep 1
  fi
}

function get_work_dir()
{
  ################
  # /kpcos/distro/huangdi/releases/1.02/targets/x86/64/bootstrap/preinstall/download.sh
  # /kpcos/distro/huangdi/bootstrap.sh
  ################

  local real_path=$(realpath $0)
  GLB_WORK_DIR=$(dirname "$real_path")
  log "WORK DIR is [$GLB_WORK_DIR]"

  GLB_PREINSTALL_ROOT="$GLB_WORK_DIR"
  log "PREINSTALL ROOT DIR is [$GLB_PREINSTALL_ROOT]"

  GLB_PREINSTALL_LIST="$1"
  log "GLB_PREINSTALL_LIST=[$GLB_PREINSTALL_LIST]"
}

# check WAN interface
function check_wan_iface()
{
  local COUNTER=0
  dev_array="$(ip route | awk '/default/ {print $5}')"
  iface_dev=$(echo $dev_array | awk '{print $1}')
  while [ "${iface_dev}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get default route device interface, exit now"
      exit 1
    fi
    log "get default route device interface again"
    dev_array="$(ip route | awk '/default/ {print $5}')"
    iface_dev=$(echo $dev_array | awk '{print $1}')
  done

  COUNTER=0
  local WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, exit now"
      exit 1
    fi
    log "get WAN IP address again"
    WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  done
  log "WAN IP=[${WAN_IP}]"
}

# get preinstall packages
function get_preinstall_pkgs()
{
  if [ ! -f $GLB_PREINSTALL_LIST ]; then
    log "no file $GLB_PREINSTALL_LIST , return now"
    return 1
  fi

  declare_i_arr lists
  while IFS= read -r line;
  do
    add_i_arr_el lists "$line"
  done <$GLB_PREINSTALL_LIST

  local i=0
  get_i_arr_indices lists indices
  for i in $indices
  do
    get_i_arr_val lists $i line
    #log "lists[$i]=[${line}]"
    local name=$(echo ${line} | awk '{print $1}')
    local url=$(echo ${line} | awk '{print $2}')
    #log "name=[$name]"
    #log "url=[$url]"
    case "$name" in
      "#"* )
        #log "it's comment"
        ;;
      "" )
        #log "it's empty line"
        ;;
      * )
        log "name=[$name]"
        log "url=[$url]"
        filename="${url##*/}"
        if [ "${filename}" != "" ]; then
          md5_file="$GLB_PREINSTALL_ROOT"/${name}.md5

          need_dl="yes"
          md5=""

          if [ -f $md5_file ]; then
            md5=$(cat $md5_file)
          fi
          log "stored md5=[$md5]"

          # check if $filename exist
          if [ -f $filename ]; then
            MD5SUM=$(md5sum $filename | awk '{print $1}')
            if [ "$MD5SUM" != "$md5" ]; then
              log "File $filename is incorrect, download again!"
              rm -f $filename
              need_dl="yes"
            else
              log "File $filename is correct"
              need_dl="no"
            fi
          fi

          if [ "$need_dl" != "no" ]; then
            log "curl -o $filename -L $url"
            curl -o $filename -L $url
          fi

          if [ ! -f $filename ]; then
            echo "No file $filename"
            exit 1
          fi

          if [ ! -f $md5_file ]; then
            MD5SUM=$(md5sum $filename | awk '{print $1}')
            echo "$MD5SUM" >$md5_file
          fi
          md5=$(cat $md5_file)

          MD5SUM=$(md5sum $filename | awk '{print $1}')
          if [ "$MD5SUM" != "$md5" ]; then
            echo "File $filename is incorrect, md5_calc=[$MD5SUM] md5=[$md5]"
            exit 1
          fi
        fi
        ;;
    esac
  done
}

# 0. init scripts
log_init
if [ x"$1" == x ]; then
  log "No args! usage: $0 [preinstall-list-file]"
  exit 1
fi
get_work_dir "$1"
cd "$GLB_WORK_DIR"
check_wan_iface
get_preinstall_pkgs

exit 0
